#include <iostream>
#include <string>
#include <map>
#include <vector>

#include <unistd.h>
#include <stdlib.h>

#include "redis_cluster.h"
#include "redis_conn.h"
using namespace std;

int main(int argc, char* argv[])
{
	if (argc < 3)
	{
		cout<<"usage:./set server(ip:port) count"<<endl;
		return 0;
	}

	vector<string> server;
	string serverarg = argv[1];
	RedisConn::stringSplit(serverarg,":",server);
	if (server.size() < 2)
	{
		cout<<"server format error,ip:port"<<endl;
		return 0;
	}
	unsigned int port = atoi(server[1].c_str());

    RedisCluster* pCluster = RedisCluster::instance();
    ClusterNode node(server[0],port);
    vector<ClusterNode> vnodes;
    vnodes.push_back(node);

    struct timeval tm;
    tm.tv_sec = 1;
    tm.tv_usec = 0;

    if (!pCluster->loadSlots(vnodes,tm))
	{
        cout<<"init error"<<endl;
		return 0;
	}

    map<SlotRange,vector<ClusterNode> >* pNodes = pCluster->getNodes();
    map<ClusterNode,RedisConn*>* pConns = pCluster->getConns();
    map<SlotRange,vector<ClusterNode> >::iterator itN;
    map<ClusterNode,RedisConn*>::iterator itC;
    cout<<"Nodes:"<<endl;
    for (itN = pNodes->begin(); itN != pNodes->end(); ++itN)
    {
        vector<ClusterNode>::iterator it;
		cout<<itN->first.m_min<<" - "<<itN->first.m_max << ":" << endl;
        for (it = itN->second.begin(); it != itN->second.end(); ++it)
        {
            cout<<it->m_ip<<":"<<it->m_port<<":"<<it->m_id<<endl;
        }
    }

    cout<<"Conns:"<<endl;
    for (itC = pConns->begin(); itC != pConns->end(); ++itC)
    {
        cout<<itC->first.m_ip<<":"<<itC->first.m_port<<":"<<itC->first.m_id<<endl;
    }
	int count = atoi(argv[2]);
	char buf[64] = {0};
	string pref("aaa");
	bool bOk = false;
	for (int i = 0; i < count; ++i)
	{
		sprintf(buf,"%s_%d",pref.c_str(),i);
		cout<<"set :"<<buf<<endl;
		string key(buf);
		RedisConn* pConn = pCluster->getConn(key);
		if (pConn == NULL)
		{
			cout<<"cluster getConn failed"<<endl;
			break;
		}
		
		bOk = pConn->setKeyValue(key,key,"36000");
		if (bOk)
			cout<<"set ok"<<endl;
		else
			cout<<"set fail"<<endl;
	}

    pCluster = NULL;
    RedisCluster::release();
    return 0;
}

